package conlon.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import conlon.constant.Constant;
import conlon.utils.ServiceThreadLocal;
import conlon.utils.SnowflakeIdWorker;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

/**
 * @author ld
 */
@Slf4j
@Component
public class BaseEntityDefaultValueSetter implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        Date now = new Date();
        Long userId = Optional.ofNullable(ServiceThreadLocal.getUserId()).orElse(0L);
        String userName = Optional.ofNullable(ServiceThreadLocal.getUserName()).orElse("system");
        this.strictInsertFill(metaObject, "createdUserId", Long.class, userId);
        this.strictInsertFill(metaObject, "createdUserName", String.class, userName);
        this.strictInsertFill(metaObject, "createdTime", Date.class, now);
        this.strictInsertFill(metaObject, "modifiedUserId", Long.class, userId);
        this.strictInsertFill(metaObject, "modifiedUserName", String.class, userName);
        this.strictInsertFill(metaObject, "modifiedTime", Date.class, now);
        this.strictInsertFill(metaObject, "version", Integer.class, 0);
        this.strictInsertFill(metaObject, "deleted", Integer.class, Constant.DELETE_DISABLE);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        LocalDateTime now = LocalDateTime.now();
        Long userId = Optional.ofNullable(ServiceThreadLocal.getUserId()).orElse(0L);
        String userName = Optional.ofNullable(ServiceThreadLocal.getUserName()).orElse("system");
        metaObject.setValue("modifiedUserId", userId);
        metaObject.setValue("modifiedUserName", userName);
        metaObject.setValue("modifiedTime", now);
    }
}